<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" alt="" class="preview" v-if="avatar" />
      <img
        src="../../../assets/images/avatar.jpg"
        alt=""
        class="preview"
        v-else
      />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          type="file"
          name=""
          id=""
          style="display: none"
          @change="getImage"
          ref="inpflie"
        />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="avatar === ''"
          @click="uploadImage"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: "UserAvatar",
  data() {
    return {
      avatar: "",
    };
  },
  methods: {
    chooseImg() {
      this.$refs.inpflie.click();
    },
    getImage(e) {
    //   console.log(e);
      const files = e.target.files;
      if (files.length !== 0) {
        // console.log(files[0]);
        //创建FileReader对象
        const reader = new FileReader();
        // 调用readAsDataURL函数读取文件内容
        reader.readAsDataURL(files[0]);
        // 监听onload事件,读取完成触发回调函数
        reader.addEventListener("load", () => {
          // 获取到base64字符串,储存到data中
          this.avatar = reader.result;
        });
      } else {
        this.avatar = "";
      }
    },
    async uploadImage() {
      const { data: res } = await this.$http.patch("/my/update/avatar", {
        avatar: this.avatar,
      });
      // console.log(res);
      if (res.code !== 0) return this.$message.error(res.message);
      this.$message.success(res.message);
      // 更新得到vuex中
      this.$store.dispatch("initUserInfo");
      //将avatar设置为空
      this.avatar = "";
    },
  },
};
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
